package com.mark.springboot.controller;


import com.mark.springboot.service.GenerateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @author Gavin
 * @description
 * @date 2020-09-10 07:21
 * @return
 * @throws
 * @since
 */
@RestController
public class GenerateController {
    @Autowired
    GenerateService generateService;

    @Value("${DBName}")
    private String dbName;

    @RequestMapping("/generate")
    public void generate(HttpServletResponse response) {
        generateService.getTableInfo(dbName);

        buildExcelDocument(response, "temp.doc", dbName);
    }

    /**
     * 读取并导出文件
     */
    private void buildExcelDocument(HttpServletResponse response, String filePath, String dbName) {

        if (filePath.contains("%")) {
            try {
                filePath = URLDecoder.decode(filePath, "UTF-8");
            }
            catch (UnsupportedEncodingException e) {
                e.fillInStackTrace();
            }
        }
        if (filePath.contains("%")) {
            try {
                filePath = URLDecoder.decode(filePath, "UTF-8");
            }
            catch (UnsupportedEncodingException e) {
                e.fillInStackTrace();
            }
        }

        ServletOutputStream out = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(new File(filePath));
            String[] dir = filePath.split("/");
            String fileName = dir[dir.length - 1];
            String[] array = fileName.split("[.]");
            String fileType = array[array.length - 1].toLowerCase();
            //设置文件ContentType类型
            if ("jpg,jepg,gif,png".contains(fileType)) {
                //图片类型
                response.setContentType("image/" + fileType);
            } else if ("pdf".contains(fileType)) {
                //pdf类型
                response.setContentType("application/pdf");
            } else {//自动判断下载文件类型
                response.setContentType("multipart/form-data");
            }
            //设置文件头：最后一个参数是设置下载文件名
            response.setHeader("Content-Disposition", "attachment;fileName=" + dbName + ".doc");
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (out!=null){
                    out.close();
                }
                if (in!=null){
                    in.close();
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            //删除缓存文件
            File file = new File("temp.doc");
            file.delete();
        }
    }
}
